<template>
  <div class="table-box card">
    <div class="ed-head">
      <span class="title">{{ documentStatus === "edit" ? "修改" : documentStatus === "add" ? "新增" : "" }}报损订单</span>
      <el-icon class="pointer" @click="router.go(-1)"><CloseBold /></el-icon>
    </div>
    <el-form :model="purchaseForm" label-width="120px" :rules="couponRules" ref="ruleFormRef" :inline="true">
      <el-form-item label="报损单编号" prop="orderNo">
        <el-input class="width240" v-model="purchaseForm.orderNo" disabled placeholder="系统自动生成" />
      </el-form-item>
      <!-- <el-form-item label="物流单号" prop="trackingNo">
        <el-input class="width240" v-model="purchaseForm.trackingNo" />
      </el-form-item> -->
      <el-form-item label="报损日期" prop="outDate">
        <el-date-picker class="width240" v-model="purchaseForm.outDate" type="date" value-format="YYYY-MM-DD" />
      </el-form-item>
      <!-- lai后面添加 -->
      <el-form-item label="报损仓库" prop="houseId">
        <el-select :disabled="documentStatus !== 'add'" class="width240" v-model="purchaseForm.houseId" placeholder="请选择">
          <el-option v-for="item in storeList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报损部门" prop="departmentId">
        <el-select class="width240" v-model="purchaseForm.departmentId" placeholder="请选择">
          <el-option v-for="item in departmentList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报损人" prop="staffId">
        <el-select class="width240" v-model="purchaseForm.staffId" placeholder="请选择">
          <el-option v-for="item in staffList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="报损类型" prop="customerId">
        <el-select style="width: 240px" v-model="purchaseForm.customerId" placeholder="请选择">
          <el-option v-for="item in customList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="库管员" prop="houseStaffId">
        <el-select class="width240" v-model="purchaseForm.houseStaffId" placeholder="请选择">
          <el-option v-for="item in staffList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input class="width240" v-model="purchaseForm.remark" placeholder="请填写" :rows="1" type="textarea" />
      </el-form-item>
    </el-form>
    <ProTable
      ref="proTable"
      row-key="id"
      :columns="columns"
      :data="purchaseForm.stockoutdetailList"
      :pagination="false"
      :is-card="false"
      show-summary
      :summary-method="getSummaries"
      :tool-button="documentStatus !== 'audited'"
    >
      <template #tableHeader>
        <el-button v-if="documentStatus !== 'audited'" type="primary" @click="openSelectTreeTable('选择原料')">
          添加原料
        </el-button>
      </template>
      <template #toolButton>
        <!-- 待审核才能确认收货 -->
        <el-button v-if="!purchaseForm.checkFlag || documentStatus !== 'add'" type="primary" @click="onSubmitGoods">
          保存并审核
        </el-button>

        <el-button v-if="documentStatus !== 'audited'" @click="onSubmit" type="primary"> 保存 </el-button>
        <el-button v-if="documentStatus !== 'audited'" @click="router.go(-1)"> 返回 </el-button>
      </template>
      <template #operate="scope">
        <div class="flx-justify-between">
          <el-icon size="18" color="#169D82" @click="add"><Plus /></el-icon>
          <el-icon @click="delSpecRow(scope.$index)" size="18" color="#f00"><Minus /></el-icon>
        </div>
      </template>
      <template #barcode="scope">
        <el-input
          class="w100"
          v-model="scope.row.barcode"
          @change="onSearchCode"
          :ref="'input' + String(scope.$index) + String(1)"
          :disabled="documentStatus === 'audited'"
          @keyup.enter="handleKeyup($event, scope.$index, 1)"
        >
          <template #append>
            <el-button
              type="primary"
              :icon="MoreFilled"
              @click="openSelectTreeTable('选择原料')"
              :disabled="documentStatus === 'audited'"
            />
          </template>
        </el-input>
      </template>
      <template #quantity="scope">
        <el-input-number
          class="w100"
          v-model="scope.row.quantity"
          :controls="false"
          :precision="2"
          :min="0"
          :disabled="documentStatus === 'audited'"
          @change="onChangeAmo(scope.$index)"
          :ref="'input' + String(scope.$index) + String(2)"
          @focus="(event:any) => event.target.select()"
          @keyup.enter="handleKeyup($event, scope.$index, 2)"
        />
      </template>
      <!-- <template #price="scope">
        <el-input-number
          class="w100"
          :controls="false"
          :precision="2"
          v-model="scope.row.price"
          :disabled="documentStatus === 'audited'"
          @change="onChangeAmo(scope.$index)"
          :ref="'input' + String(scope.$index) + String(3)"
          @focus="(event:any) => event.target.select()"
          @keyup.enter="handleKeyup($event, scope.$index, 3)"
        />
      </template> -->
      <template #remark="{ row }">
        <el-input class="w100" v-model="row.remark" :disabled="documentStatus === 'audited'" />
      </template>
      <template #amount="{ row }">
        {{ row.costPrice * row.quantity }}
      </template>
      <template #customerId="{ row }">
        <el-select style="width: 100%" v-model="row.customerId" placeholder="请选择">
          <el-option v-for="item in customList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </template>
    </ProTable>
    <SelectTreeTable @selected-list="handleSelectedTreeList" ref="selectTreeTableRef" />
  </div>
</template>
<script setup lang="ts" name="stockOutEdit">
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import SelectTreeTable from "@/components/SelectTreeData/index.vue";
import {
  createStockOut,
  editStockOut,
  getStockin,
  getSupplierList,
  getWaresCategoryList,
  getWaresList,
  getStorehouseList,
  getInventoryGoodsList,
  getCustomList,
  getStockOut,
  checkStockOut
} from "@/api/modules/inventory";

import ProTable from "@/components/ProTable/index.vue";
import { MoreFilled } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import { replaceArrayItems } from "@/utils";
import { ColumnProps } from "@/components/ProTable/interface";
import { ElMessage, TableColumnCtx } from "element-plus";
import { getDepartMentList, getStaffList } from "@/api/modules/operation";
import { formatDate } from "@/utils/date-formatter";
import { Inventory } from "@/api/interface";

const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const documentStatus = ref("add");
const purchaseForm = reactive<any>({
  id: 0,
  type: 2,
  // orderType: 1,
  orderNo: "",
  // supplierId: "",
  outDate: formatDate(0, "start", "yyyy-MM-dd"),
  trackingNo: "",
  status: 1,
  checkFlag: false,
  remark: "",
  sourceId: "",
  printStatus: 0,
  stockoutdetailList: [],
  // 后面添加
  houseId: 0,
  departmentId: null,
  staffId: null,
  // customerId: null,
  houseStaffId: null
});
const couponRules = reactive({
  stockoutdetailList: [{ required: true, message: "请添加原料" }],
  departmentId: [{ required: true, message: "请选择部门" }],
  staffId: [{ required: true, message: "请选择领用人" }]
  // houseStaffId: [{ required: true, message: "请选择库管人" }]
  // customerId: [{ required: true, message: "请领用类型" }]
});

const delSpecRow = (index: number) => {
  purchaseForm.stockoutdetailList.splice(index, 1);
};

const columns: ColumnProps<any>[] = [
  { type: "index", label: "序号", width: 60 },
  { prop: "operate", label: "操作", width: 80 },
  { prop: "barcode", label: "编码", minWidth: 220 },
  { prop: "goodsName", label: "名称", minWidth: 140 },
  { prop: "productName", label: "规格", width: 110 },
  { prop: "quantity", label: "数量", width: 110 },
  { prop: "costPrice", label: "单价", minWidth: 120 },
  { prop: "amount", label: "金额", width: 110 },
  { prop: "planQuantity", label: "当前库存", width: 110 },
  { prop: "unitName", label: "单位名称", width: 110 },
  { prop: "customerId", label: "报损类型", width: 150 },
  { prop: "remark", label: "备注", width: 180 }
];

const onSearchCode = (value: string | number) => {
  if (Object.entries(value).length !== 0) {
    openSelectTreeTable("选择原料", value);
  }
};

const handleSelectedTreeList = (val: any) => {
  if (val.list.length > 0) {
    let list = val.list.map((im: any) => {
      return {
        goodsName: im.name,
        goodsId: im.id,
        products: im.productName,
        productsId: im.productsId,
        productName: im.productName,
        quantity: 1,
        barcode: im.barcode,
        price: im.purPrice,
        costPrice: im.costPrice,
        amount: im.purPrice,
        taxRate: 0,
        isGift: false,
        giftQuantity: 0,
        planQuantity: im.planQuantity,
        unitName: im.unitName,
        remark: "",
        customerId: customList.value.length > 0 ? customList.value[0].id : null
      };
    });
    purchaseForm.stockoutdetailList = replaceArrayItems(list, purchaseForm.stockoutdetailList, "goodsId");
    // purchaseForm.stockoutdetailList = list;
  }
};

interface SummaryMethodProps<T = Inventory.ResPurchaseList> {
  columns: TableColumnCtx<T>[];
  data: T[];
}

const add = () => {
  purchaseForm.stockoutdetailList.push({
    goodsName: "",
    goodsId: 0,
    products: "",
    productsId: 0,
    productName: 0,
    quantity: 0,
    price: 0,
    amount: 0,
    taxRate: 0,
    isGift: false,
    giftQuantity: 0,
    remark: "",
    // customerId: customList.value[0].id
    customerId: customList.value.length > 0 ? customList.value[0].id : null
  });
};

const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;
  const props: string[] = ["quantity", "amount", "giftQuantity"];
  const sums: string[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (!props.includes(column.property)) {
      sums[index] = "";
      return;
    }

    let valuesToSum: number[] = [];
    data.forEach(item => {
      if (column.property === "quantity" && item.isGift) {
        return; // 如果isGift为true，则不统计quantity
      }
      if (column.property === "amount" && item.isGift) {
        return; // 如果isGift为true，则不统计amount
      }
      if (column.property === "giftQuantity" && !item.isGift) {
        return; // 如果isGift为false，则不统计giftQuantity
      }
      const value = Number(item[column.property]);
      if (!Number.isNaN(value)) {
        valuesToSum.push(value);
      }
    });

    if (valuesToSum.length > 0) {
      sums[index] = `${valuesToSum.reduce((prev, curr) => prev + curr, 0)}`;
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

const onSubmit = () => {
  if (customList.value.length < 1) return ElMessage.error("请先添加报损类型");

  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (documentStatus.value === "edit") {
        await editStockOut(purchaseForm).then(() => {
          router.push({
            path: "/stock/breakage",
            query: {
              upList: true
            }
          });
        });
      } else {
        await createStockOut(purchaseForm).then(() => {
          router.push({
            path: "/stock/breakage",
            query: {
              upList: true
            }
          });
        });
      }
    } catch (error) {
      console.log(error);
    }
  });
};

// 确认收货并审核
const onSubmitGoods = async () => {
  if (purchaseForm.stockoutdetailList.length < 1) return ElMessage.error("请添加原料");
  if (customList.value.length < 1) return ElMessage.error("请先添加报损类型");
  await ruleFormRef.value!.validate();
  await checkStockOut(purchaseForm);
  // console.log(res);
  ElMessage.success("审核成功");
  router.push({
    path: "/stock/breakage",
    query: {
      upList: true
    }
  });
};

const onChangeAmo = (index: number) => {
  purchaseForm.stockoutdetailList[index].amount = (
    purchaseForm.stockoutdetailList[index].price * purchaseForm.stockoutdetailList[index].quantity
  ).toFixed(2);
};
const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);
const openSelectTreeTable = (title: string, searchVal?: string | number) => {
  const params = {
    title,
    isView: false,
    searchVal,
    index: 0,
    mate: "productsId",
    selTags: purchaseForm.stockoutdetailList.map((i: any) => {
      i.name = i.goodsName;
      i.id = i.productsId;
      return i;
    }),
    columns: [
      { type: "selection", width: 80 },
      { prop: "barcode", label: "编码", align: "left", width: 200 },
      { prop: "name", label: "原料名称", align: "left", minWidth: 220 },
      { prop: "productName", label: "规格", align: "left", minWidth: 100 },
      { prop: "unitName", label: "单位", align: "left", minWidth: 160 },
      // { prop: "posPrice", label: "原料价格", minWidth: 120 }
      { prop: "purPrice", label: "采购价格", minWidth: 120 }
    ],
    idName: "goodsCategoryId",
    treeApi: getWaresCategoryList,
    api: getInventoryGoodsList,
    apiParams: { houseId: purchaseForm.houseId }
  };
  selectTreeTableRef.value?.acceptParams(params);
};
const supplierList = ref([]);
// const storeList = ref([]);
const { proxy } = getCurrentInstance();
const refsInputName = ref("");

const handleKeyup = (event: any, index: number, cellIndex: number) => {
  if (cellIndex < 3) {
    refsInputName.value = "input" + String(index) + String(cellIndex + 1);
  } else {
    refsInputName.value = "input" + String(index + 1) + "1";
  }
  if (proxy.$refs[refsInputName.value]) {
    nextTick(() => {
      event.target.blur();
      proxy.$refs[refsInputName.value].focus();
    });
  }
};

onMounted(async () => {
  try {
    const [supplier] = await Promise.all([
      getSupplierList(),
      // getStoreList()
      onShowStore(),
      getDepartmentList(),
      getStaffsList(),
      getCustomsList()
      // useSelectStore().getDic("DiscountType")
    ]);
    supplierList.value = supplier.data.list;
    // storeList.value = store.data.list;
    if (route.query.id) {
      getStockOut({ id: route.query.id }).then(res => {
        if (res.data.checkFlag) {
          documentStatus.value = "audited";
        } else {
          documentStatus.value = "edit";
        }
        Object.keys(purchaseForm).forEach(key => {
          if (res.data.hasOwnProperty(key)) {
            purchaseForm[key] = res.data[key];
          }
        });
      });
    } else {
      // purchaseForm.storeId = store.data.list[0].id;
      purchaseForm.supplierId = supplier.data.list[0].id;
    }
  } catch (error) {
    // 错误处理逻辑
    console.error("An error occurred:", error);
  }
});

// 获取仓库列表
const storeList = ref<any[]>([]);
// const defaultHouserId = ref("");
const onShowStore = async () => {
  const res = await getStorehouseList({ pageNum: 1, pageSize: 9999 });
  storeList.value = res.data.list;
  storeList.value.forEach(v => {
    if (v.isDefault) {
      purchaseForm.houseId = v.id;
    }
  });
};

// 部门列表
const departmentList = ref<any[]>([]);
const getDepartmentList = async () => {
  const res = await getDepartMentList({ pageNum: 1, pageSize: 9999 });
  departmentList.value = res.data.list;
  purchaseForm.departmentId = res.data.list[0].id;
};
// 员工列表
const staffList = ref<any[]>([]);
const getStaffsList = async () => {
  const res = await getStaffList({ pageNum: 1, pageSize: 9999 });
  staffList.value = res.data.list;
  purchaseForm.staffId = res.data.list[0].id;
};
// 类型列表
const customList = ref<any[]>([]);
const getCustomsList = async () => {
  const res = await getCustomList({ pageNum: 1, pageSize: 9999, commTypeId: 2 });
  customList.value = res.data.list;
};
</script>

<style lang="scss" scoped></style>
